package com.controller;

import com.domain.Blogger;
import com.service.BloggerService;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 博主登陆相关
 */
@Log4j2
@Controller
@RequestMapping("/blogger")
public class BloggerController {
    @Resource
    private BloggerService bloggerService;

    @RequestMapping("/login")
    public String login(Blogger blogger, HttpServletRequest request) {
        String username = blogger.getUserName();
        String password = blogger.getPassword();
        log.info("info:登录名：" + username + "\t登陆时间：" + new Date());
        log.error("error:登录名：" + username + "\t登陆时间：" + new Date());
        log.error("我是error");
//        String pw = CryptographyUtil.md5(password, "salt");
        //1.认证的核心组件：获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        //2.将登陆表单封装成token对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //记住我
        //token.setRememberMe(true);
        try {
            //3.让shiro框架进行登陆验证
            subject.login(token);
            if(subject.isAuthenticated()) {
                return "redirect:/admin/main.jsp";
            }
            return "login";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            request.setAttribute("blogger", blogger);
            request.setAttribute("errorInfo", "用户名或密码错误！");
        }
        return "login";
    }

    @RequestMapping("/aboutMe")
    public ModelAndView aboutMe() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("blogger", bloggerService.find());
        mv.addObject("mainPage", "foreground/blogger/info.jsp");
        mv.addObject("pageTitle", "关于博主——个人博客系统");
        mv.setViewName("index");
        return mv;
    }
}
